#！/usr/bin/python3

# try:执行代码
# except:发生异常时执行代码
# else：无异常时执行代码
# final：不管有无异常都执行代码

def runoob():
    "no content"

try:
    runoob()
except AssertionError as error:  # as为指定别名
    print(error)
    try:
        with open("file.txt") as file:
            read_data = file.read()
            print(read_data)
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print("always print this parse")
print ("------------------------")


from os import name
import sys

# while True:
#     try:
#         x = int(input("please input a number:"))
#         break;
#     except ValueError:
#         print("your input is not a number, please try again......")
#     except (RuntimeError, TypeError, NameError): # 以元组形式捕获多个异常
#         pass
#     except:     #最后一个except子句可以忽略异常的名称，它将被当作通配符使用
#         print("Unexpected error:", sys.exc_info()[0])

try:
    a = input("输入一个数：")
    #判断用户输入的是否为数字
    if(not a.isdigit()):
        raise ValueError("a 必须是数字") # raise 可以手动引发一个异常
except ValueError as e:
    print("引发异常：",repr(e))
print ("------------------------")

# raise 抛出异常类型和说明
x = 2
if x>5:
    raise Exception("x can't be bigger than 5, x is:{}".format(x)) # 运行时会直接输出到终端, 程序终止

print ("------------------------")

try:
    raise NameError("test for raise")
except NameError as name_error:
    print("An except flew by:{0}".format(name_error))
print ("------------------------")

# with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:
for line in open("foo.txt"):  # 可以直接读取到每一行
    print(line,end = " ")
    print()
print ("------------------------")

with open("foo.txt") as f:
    for line in f:
        print(line,end = " ")
        print()